//
//  JddNavigationController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddNavigationController.h"
#import <QuartzCore/QuartzCore.h>
#import "JddCommonFunction.h"
#import "JddBaseViewController.h"
#import "JddGlobal.h"

@interface JddNavigationController () <UIGestureRecognizerDelegate, UINavigationControllerDelegate>

@end

@implementation JddNavigationController
GET_INSTANCE_VIEW_IMPLEMENT(JddNavigationController)

- (void)dealloc {
    self.interactivePopGestureRecognizer.delegate = nil;
    self.delegate = nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0xdd161b)];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    __weak typeof(self) weakSelf = self;
    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.interactivePopGestureRecognizer.delegate = weakSelf;
        self.delegate = weakSelf;
    }
}

#pragma mark -- Override func

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.interactivePopGestureRecognizer.enabled = NO;
    }
    [[JddGlobal sharedInstance].tabBar hide];
    [super pushViewController:viewController animated:animated];
}

#pragma mark -- UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated
{
    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        if ([navigationController.viewControllers count] == 1) {
            // Disable the interactive pop gesture in the rootViewController of navigationController
            navigationController.interactivePopGestureRecognizer.enabled = NO;
        } else {
            // Enable the interactive pop gesture
            navigationController.interactivePopGestureRecognizer.enabled = YES;
        }
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    UIViewController *vc = [self visibleViewController];
    if (vc && [vc isKindOfClass:[JddBaseViewController class]]) {
        if ([(JddBaseViewController *)vc hideBackItem]) {
            return NO;
        }
        return YES;
    }
    return YES;
}

@end
